#include "SpriteList.h"

class SpriteList_Cleaner {
public:
    ~SpriteList_Cleaner() {
        SpriteList::destroy();
    }
} SpriteList_cleaner_instance;

SpriteList* SpriteList::instance = NULL;

SpriteList::SpriteList()
{
    if (Debug::test(DEBUG_CREATE_DELETE)) {
        cout << "SpriteList Created" << endl;
    }
}

SpriteList* SpriteList::get_instance() {
    if(!instance) {
        instance = new SpriteList();
    }
    return instance;
}

void SpriteList::destroy() {
    if( instance) {
        delete(instance);
        instance = NULL;
        if (Debug::test(DEBUG_CREATE_DELETE)) {
            cout << "SpriteList Destroyed" << endl;
        }
    }
}


bool SpriteList::add(uint imgId, uint spriteId, SDL_Rect rect)
{
    SpriteListItem newItem;
    newItem.m_imgId = imgId;
    newItem.m_spriteId = spriteId;
    newItem.m_rect = rect;
    newItem.m_id = ID_Manager::get_instance().get_ID();
    m_mutex.lock();
    m_sprites.push_back(newItem);
    m_mutex.unlock();
    if (Debug::test(DEBUG_ADD_REMOVE)) {
        cout << "added new sprite : " << newItem.m_rect.x << " " << newItem.m_rect.y << " " <<
            newItem.m_rect.w << " " << newItem.m_rect.h << endl;
    }
    return true;
}

bool SpriteList::find(uint spriteId, uint &imgId, RectInfo &rect)
{
    list<SpriteListItem>::iterator i;
    m_mutex.lock();
   for(i=m_sprites.begin(); i != m_sprites.end(); ++i) {
       if(i->m_spriteId == spriteId) {
           imgId = i->m_imgId;
           spriteId = i->m_spriteId;
           m_mutex.unlock();
       }
   }
   m_mutex.unlock();
   return true;

}

SpriteListItem &SpriteList::operator[](uint spriteId)
{
    list<SpriteListItem>::iterator i;
    m_mutex.lock();
    for(i=m_sprites.begin(); i != m_sprites.end(); ++i) {
        if(i->m_spriteId == spriteId) {
            break;
        }
    }

    if (i == m_sprites.end()) {
        throw runtime_error("SpriteListItem &SpriteList::operator[](uint spriteId) : Could not find sprite " + formatInt(spriteId,4));
    }

    m_mutex.unlock();
    return *i;
}

